﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Policy;
using System.Web;
using System.Web.Mvc;
using Chbl.Controllers;
using Chbl.DAL;
using Chbl.DataAccess.DTO;
using Chbl.Helpers;
using Chbl.Models;

namespace Chbl.ViewModels
{
    public class HomeViewModel
    {
        private const int RecordsAmountPerPage = 10;
        private int _latestTourNumber;
        private List<string> _latestPhotos;
        private IEnumerable<MediaObject> _latestPhotoObjects;
        private readonly UrlHelper _urlHelper;
        private List<int> _tourNumbers;

        public HomeViewModel(UrlHelper urlHelper, IEnumerable<MediaObject> latestPhotoObjects)
        {
            GamesSchedule = new Dictionary<SeasonDivision, ScheduleViewModel>();
            TeamStandings = new Dictionary<SeasonDivision, IEnumerable<TeamStandingViewModel>>();
            TopNews = new List<Article>();
            Articles = new List<Article>();
            BirthdayThisMonthMembers = new List<Member>();
            _latestPhotoObjects = latestPhotoObjects;
            _urlHelper = urlHelper;

        }
        public Season CurrentSeason { get; private set; }        
        public IEnumerable<KeyValuePair<SeasonDivision, IEnumerable<Game>>> LatestTourSchedule 
        {
            get
            {
                return GamesSchedule.Select(
                    record => new KeyValuePair<SeasonDivision, IEnumerable<Game>>(
                        record.Key, 
                        record.Value.Games.Where(game => game.TourNumber == _latestTourNumber)));
            }
        }
        public IDictionary<SeasonDivision, IEnumerable<TeamStandingViewModel>> TeamStandings { get; private set; }
        public IEnumerable<Article> TopNews { get; private set; }
        public IEnumerable<Article> Articles { get; private set; }
        public IEnumerable<QualifyingGamesViewModel> QualifyingGames { get; set; }
        private IEnumerable<Member> BirthdayThisMonthMembers { get; set; }
        public IEnumerable<string> BirthdayThisMonth
        {
            get
            {
                return
                    BirthdayThisMonthMembers.Select(
                        m => string.Format("{0} - {1}", m.Fio, BirthdayHelper.GetBirthdayMessage(m.BirthDate.Value)));
            }
        }

        public IEnumerable<string> LatestPhotos
        {
            get { return _latestPhotos; }
        }

        public IEnumerable<SelectListItem> TourNumbers
        {
            get
            {
                return _tourNumbers.Select(t => new SelectListItem
                                             {
                                                 Selected = (t == _latestTourNumber),
                                                 Text = t.ToString(),
                                                 Value = t.ToString()
                                             });
            }
        }

        public void LoadData(ChblDb db)
        {
            _latestTourNumber = db.Settings.First().CurrentTour;
            _tourNumbers = db.Games.Select(g => g.TourNumber).Distinct().ToList();

            var latestSeasonNumber = db.Seasons.Max(s => s.Number);
            CurrentSeason = db.Seasons.Include("SeasonDivisions").Where(s => s.Number == latestSeasonNumber).Single();
            foreach (var seasonDivision in CurrentSeason.SeasonDivisions)
            {
                GamesSchedule.Add(
                    seasonDivision,
                    new ScheduleViewModel(
                        ScheduleController.GetGamesSchedule(db, seasonDivision.SeasonDivisionId),
                        DateTime.Parse(seasonDivision.Division.GamesStartTime)));
            }

            TopNews = GetTopNews(db);
            //todo: implement paging
            Articles = db.Articles.OrderByDescending(a => a.Date).Take(RecordsAmountPerPage);
            BirthdayThisMonthMembers =
                db.Members.Where(m => m.BirthDate.HasValue && m.BirthDate.Value.Month == DateTime.Today.Month && m.BirthDate.Value.Day >= DateTime.Today.Day).OrderBy(m => m.Fio).Take(RecordsAmountPerPage);
            LoadStandings();
            LoadLatestPhotos();
        }
        
        public IDictionary<SeasonDivision, ScheduleViewModel> GamesSchedule { get; set; }

        private void LoadLatestPhotos()
        {            
            string filePath = ConfigurationManager.AppSettings["GPSFilePathFormat"];
            _latestPhotos =
                _latestPhotoObjects.Select(media => _urlHelper.Content(string.Format(filePath, media.DirectoryName, media.FileName))).ToList();
        }

        private static IEnumerable<Article> GetTopNews(ChblDb db)
        {
            return db.Articles.Where(a => a.isTopNews).OrderBy(a => a.TopNewsNumber);
        }

        private void LoadStandings()
        {
            foreach (var seasonDivision in CurrentSeason.SeasonDivisions)
            {
                var standings = new StandingsViewModel(seasonDivision.Teams);
                foreach (var game in GamesSchedule[seasonDivision].Games)
                {
                    standings.ProcessGame(game);
                }
                TeamStandings.Add(seasonDivision, standings.GetStandings(GamesSchedule[seasonDivision]));
            }

        }

    }
}